package org.sintec.AndroidCarConnectivity;

import java.util.Set;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class BluetoothWrapper 
{
	private activityDeviceList mContext;
	private BluetoothAdapter mBtAdapter;
	
	BluetoothWrapper(activityDeviceList context)
	{
		mContext = context;

		// Register for broadcasts when a device is discovered
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        mContext.registerReceiver(mReceiver, filter);
        
        // Get the local Bluetooth adapter
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
	}
	
	void doDiscovery()
	{
		mContext.onDiscoveryStarted();
		
		// If we're already discovering, stop it
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        // Request discover from BluetoothAdapter
        mBtAdapter.startDiscovery();
	}
	
	void doCancelDiscovery()
	{
		// Cancel discovery because it's costly and we're about to connect
        mBtAdapter.cancelDiscovery();
	}
	
	Set<BluetoothDevice> getPairedDevices()
	{
		return mBtAdapter.getBondedDevices();
	}
	
	public BluetoothAdapter getBtAdapter()
	{
		return mBtAdapter;
	}
	// The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) 
            {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED)
                {
                    mContext.onDiscoveryDeviceFound(device);
                }
            // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) 
            {
            	mContext.onDiscoveryFinished();
            }
        }
    };
}
